//商品详情

import api from '../../../utils/api'
var app = getApp();
var host = app.globalData.host;
let animationShowHeight = 300; 
Page({

  /**
   * 页面的初始数据
   */
  data: {
    host: getApp().globalData.host,
    isloadmain:false,
    num:1,
    show_top:false,
    show_down:true,
    collect: false,
    collect_text:'收藏',
    isSelect:0,//品类默认选中项
    height:0,
    curIndex:0,
    to_detail:true,
    details:{},
    total:0,//评价总条数
    comment:[],//评论
    collect_arr:[],
    banners: [],
    animationData: {},
    showModalStatus: false,
    spec_name:[],
    spec_price:[], 
    carts:[],//购物车物品
    show_badge:false,//badge的显示
    type:'',
    sel_price:0,
    more_com:true,//是否有更多评论
  },

  /* 减少数量 */
  bindMinus: function () {
    var num = this.data.num;
    // 如果大于1时，才可以减 
    if (num > 1) {
      num--;
    }
    // 只有大于一件的时候，才能normal状态，否则disable状态 
    var minusStatus = num <= 1 ? 'disabled' : 'normal';
    // 将数值与状态写回 
    this.setData({
      num: num,
      minusStatus: minusStatus
    });
  },

  /* 增加数量 */
  bindPlus: function () {
    var num = this.data.num;
    // 不作过多考虑自增1 
    num++;
    // 只有大于一件的时候，才能normal状态，否则disable状态 
    var minusStatus = num < 1 ? 'disabled' : 'normal';
    // 将数值与状态写回 
    this.setData({
      num: num,
      minusStatus: minusStatus
    });
  }, 

  // 显示规格
  show_spec(){
    this.setData({
      show_top: !this.data.show_top,
      show_down: !this.data.show_down
    })
  },

  //选择品类
  check_spec(e){
    let spec_price = this.data.spec_price;
    let idx = e.currentTarget.dataset.index;
    let spec_type = e.currentTarget.dataset.type;
    this.setData({
      isSelect: idx,
      sel_price: spec_price[idx],
      type: spec_type
    })
  },

  // 切换选项卡
  bindTab(e){
    this.setData({
      curIndex: e.currentTarget.dataset.index
    })    
  },

  // 跳转购物车
  to_cart(){
    wx.switchTab({
      url: '../../cart/index/index'
    })
  },

  // 判断购物车是否有商品，控制badge的显示
  get_carts(){
    let val = wx.getStorageSync('carts');
    if(val.length == 0){
      this.setData({
        show_badge:false
      })
    }else{
      this.setData({
        show_badge: true
      })
    }

  },

  // 加入购物车
  addTo_cart(e){
    var that = this;
    let detail = e.currentTarget.dataset.detail;
    // 查找重复的
    var repeat = this.data.carts.find((item,index) => {
      return item.id == detail.id && (item.spec_id == that.data.isSelect);
    })

    if(repeat){
      // 如果有重复的
      let indx = this.data.carts.indexOf(repeat);
      this.data.carts[indx].num += that.data.num;
      wx.setStorageSync('carts', this.data.carts)
      
    }else{
      // 如果没有重复的
      let cart_item = {
        'id': detail.id,
        'pic': detail.pro_image,
        'name': detail.pro_name,
        'price': this.data.sel_price,
        'selected': false,
        'spec_type': this.data.type,
        'num': this.data.num,
        'spec_id': this.data.isSelect,
        'freight_id': detail.freight_id,
        'freight': detail.freight
      }
      this.data.carts.push(cart_item);
      wx.setStorageSync('carts', this.data.carts)
    }
    this.setData({
      showModalStatus:false
    })
    wx.showToast({
      title: '添加成功',
      icon: 'success',
      duration: 2000
    })

  },

  // 立即购买
  to_buy(e){
    console.log(e.currentTarget.dataset.item)
    var that = this;
    let pro= [];
    let pro_item = {
      "id": e.currentTarget.dataset.item.id,
      "name": e.currentTarget.dataset.item.pro_name,
      'pic': e.currentTarget.dataset.item.pro_image,
      "spec_id": that.data.isSelect,
      "num": that.data.num,
      'price': that.data.sel_price,
      'spec_type': that.data.type,
      'freight_id': e.currentTarget.dataset.item.freight_id,
      'freight': e.currentTarget.dataset.item.freight
    }
    pro.push(pro_item)
    wx.setStorage({
      key: "pro",
      data: pro
    })
    wx.navigateTo({
      url: '../../payment/index/index'
    })
  },

  // 显示遮罩
  showModal: function (e) {
    if (e.currentTarget.dataset.op == 'buy'){
      this.setData({
        to_detail: true
      })
    }else{
      this.setData({
        to_detail: false
      })
    }
    this.setData({
      showModalStatus: true
    })
  },

  // 隐藏遮罩层 
  hideModal: function () {
    this.setData({
      showModalStatus: false
    })
  },

  // 获取商品评价总条数
  _get_length(detail_id) {
    var that = this;
    api.request('/comment/list', 'GET', {
      pro_id: detail_id,
      page:1
    }, (res) => {
      that.setData({
        total: res.data.total
      })
    })
  },

  // 获取商品详情
  _load_details(detail_id){
    var that = this;
    api.request('/shop/product', 'GET', {
      id: detail_id
    }, (res) => {
      console.log(res.data.data);
      //获取本地缓存的收藏列表
      let arr = wx.getStorageSync('collect_arr');
      let repeat_item = arr.filter(function(item){
        return item.id == res.data.data.id
      })
      if(repeat_item.length>0){
        // 如果本地收藏列表里有该商品
        that.setData({
          collect:true
        })
      }else{
        // 如果本地收藏列表里没有该商品
        that.setData({
          collect: false
        })
      }
      that.setData({
        details: res.data.data,
        banners: res.data.data.pro_slides,
        comment: res.data.comment.data,
        spec_name: res.data.data.spec_name,
        spec_price: res.data.data.spec_price,
        sel_price: res.data.data.spec_price[0],
        type: res.data.data.spec_name[0],
        more_com: res.data.comment.has_more,
        isloadmain: true
      })
    })
  },
  
  // 收藏
  to_collect(e) {
    var that = this;
    var collect = this.data.collect;
    let item = e.currentTarget.dataset.collects;
    that.setData({
      collect: !collect
    })
    // console.log(this.data.collect)
    let collect_arr = that.data.collect_arr;
    if (this.data.collect){
      collect_arr.push(item);
    }else{
      console.log(item.id);
      // 找出收藏列表里重复的
      let repeat_arr = collect_arr.filter(function(arr_item,index){
        return arr_item.id == item.id
      })
      // 封装删除方法
      Array.prototype.remove = function (val) {
        var index = this.indexOf(val);
        if (index > -1) {
          this.splice(index, 1);
        }
      };
      repeat_arr.forEach(function(item){
        collect_arr.remove(item);
      })
      console.log(collect_arr)
    }
    console.log(that.data.collect_arr)
    //缓存到本地数据库
    wx.setStorageSync('collect_arr', collect_arr)
    wx.showToast({
      title: '操作成功',
      icon: 'success',
      duration: 2000
    })
  },

  // 获取本地收藏列表
  get_collectlist(){
    var that = this;
    let val = wx.getStorageSync('collect_arr');
    if (val.length == 0) {
      that.setData({
        collect_arr: []
      })
      wx.setStorageSync('collect_arr', that.data.collect_arr)
    }else{
      that.setData({
        collect_arr: val
      })
    }
  },

  // 图片预览
  previewImage: function (e) {
    var that = this;
    let pro_images = this.data.details.pro_images;
    for (let i = 0; i <pro_images.length;i++){
      console.log(that.data.host+pro_images[i])
      pro_images[i] = that.data.host + pro_images[i]
    }
    var current = e.target.dataset.src;
    wx.previewImage({
      current: current, // 当前显示图片的http链接  
      // urls: this.data.imgalist // 需要预览的图片http链接列表 
      urls: pro_images
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    var detail_id = options.id;
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          height: res.windowHeight - 101*0.42 + 'px'
        })
      }
    })
    //获取购物车物品
    let carts = wx.getStorageSync('carts');
    if(carts){
      that.setData({
        carts:carts
      })
    }
    // 获取商品详情
    this._load_details(detail_id)
    // 获取商品评价条数
    this._get_length(detail_id)
    
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this;
    wx.getSystemInfo({
      success: function (res) {
        animationShowHeight = res.windowHeight;
      }
    })
    that.setData({
      showModalStatus:false
    })
    this.get_carts()
    // 获取本地收藏列表
    this.get_collectlist()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    
  }
})